package com.qf.service.impl;

import com.qf.entity.Result;
import com.qf.mapper.MemberMapper;
import com.qf.mapper.OrderMapper;
import com.qf.mapper.OrderMapper1;
import com.qf.mapper.OrderSettingMapper;
import com.qf.pojo.Member;
import com.qf.pojo.Order1;
import com.qf.pojo.OrderSetting;
import com.qf.service.OrderService;
import com.qf.service.OrderService1;
import com.qf.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class OrderServiceImpl1 implements OrderService1 {

    @Autowired
    OrderMapper1 orderMapper;
    @Autowired
    OrderSettingMapper orderSettingMapper;
    @Autowired
    MemberMapper memberMapper;

    @Override
    /**
     *     体检预约
     */
    public Result order(Map map) throws Exception {
        //得到预约时间
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate,"yyyy-MM-dd");
        //根据日期查询预约设置信息
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(date);
        //检查当前日期是否进行了预约设置
        if (orderSetting == null){
            //没有预约设置
            return Result.error("该日期未开放预约");
        }
        //可预约人数和已预约人数
        Integer number = orderSetting.getNumber();
        Integer reservations = orderSetting.getReservations();
        //检查预约日期是否预约已满
        if (reservations >= number){
            //预约满了
            return Result.error("预约人数已满");
        }
        //可以预约，数据库已经预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingMapper.editReservationsByOrderDate(orderSetting);
        //得到手机号
        String phone = (String) map.get("phone");
        //检查当前用户是否为会员，根据手机号判断
        Member member = memberMapper.findByPhone(phone);
        //当前用户不是会员，需要添加到会员表
        if (member == null){
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(phone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberMapper.add(member);
        }
        //保存预约信息(会员id,预约时间,预约类型,预约状态,套餐id)到预约表
        Order1 order = new Order1(member.getId(), date,  (String)map.get("orderType"),"未到诊",
                Integer.parseInt((String)map.get("setmealId")));

        orderMapper.add(order);
        //预约成功,得到预约的id,这里的id是t_order表里的member_id
        return Result.success(order.getId());
    }

    /**
     *     根据id查询预约信息，包括体检人信息、套餐信息
     */
    public Map findById(Integer id) throws Exception {
        Map map = orderMapper.findOrderByMemberIDAndOrderDate(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }


}
